<template>
  <div class="row">
    <h2  v-if="tip" style="text-align: center">请输入要查询的用户名称</h2>
    <img v-else-if="loading" src="./img/loding.gif" class="img">
    <h2  v-else-if="noBody" style="text-align: center">查无此人</h2>
    <h2  v-else-if="error" style="text-align: center">{{errorInfo}}</h2>
    <div v-else class="card" v-for="user in list" :key="user.id">
      <a :href="user.home" target="_blank">
        <img :src="user.avatar" style='width: 100px'/>
      </a>
      <p class="card-text">{{user.name}}</p>
    </div>
  </div>
</template>

<script>
    export default {
        name: "v-list",
        data(){
          return {
            username:"",
            list:[],
            tip:true,
            loading:true,
            noBody:true,
            error:true,
            errorInfo:""
          }
        },
        methods:{
          showLoding(){
            this.tip=false;
            this.loading=true,
            this.noBody=true
            this.error=true
          },
          showList(){
            this.tip=false;
            this.loading=false,
            this.noBody=false,
            this.error=false
          },
          showNoBody(){
            this.tip=false;
            this.loading=false,
            this.noBody=true
            this.error=true
          },
          showError(){
            this.tip=false;
            this.loading=false,
            this.noBody=false,
            this.error=true
          }
        },
        mounted(){
          this.$bus.$on("searchFn",async (username)=>{
            try {
              //关闭tip 显示loading 请求前
              this.showLoding()

              //请求中
              this.username= username;
              //根据username 获取username在github平台上对应的账户
              const {items} = await this.$http.github.get("/search/users",{params:{q:this.username}})
              this.list = items.map(user => ({
                ...user,
                home:user.html_url,
                avatar:user.avatar_url,
                name:user.login
              }));

              //请求成功
              if(this.list.length > 0){
                this.showList()
              }else {
                this.showNoBody()
              }

            }catch (e) {
              this.showError()
              this.errorInfo = e.message
            }


          })
        }
    }
</script>

<style scoped>

  .img{
    border-radius: 50%;
    width: 300px;
    height: 200px;

    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
  }

  .card {
    float: left;
    width: 33.333%;
    padding: .75rem;
    margin-bottom: 2rem;
    border: 1px solid #efefef;
    text-align: center;
  }

  .card > img {
    margin-bottom: .75rem;
    border-radius: 100px;
  }

  .card-text {
    font-size: 85%;
  }

</style>
